import { lovDefineAxiosConfig } from 'utils/c7nUiConfig';
import qs from 'querystring';
import { isEmpty, isBoolean } from 'lodash';
import { isTenantRoleLevel, getCurrentOrganizationId, getCurrentTenant } from 'utils/utils';
import { filterNullValueObject } from 'utils/utils';

export const getUrlParamHref = (name): any => {
  let res;
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'); // eslint-disable-line
  var r = window.location.search.substr(1).match(reg); // eslint-disable-line
  if (r != null) {
    res = decodeURIComponent(r[2]); // eslint-disable-line
  }

  // 存在iframe的情况（工作流审批表单 - 无法获取search，只能获取hash）
  const queryIndex = (window?.frameElement as any)?.src?.indexOf('?');
  let sourceQueryParams = {};
  if (queryIndex !== -1) {
    sourceQueryParams = qs.parse((window?.frameElement as any)?.src?.substr(queryIndex + 1));
  }

  // eslint-disable-next-line no-nested-ternary
  return window?.frameElement ? sourceQueryParams?.[name] : isEmpty(res) ? '' : res;
};


export const PreviewPageUrlSuffix = 'renderview/test';
export const PreviewReleasePageUrlSuffix = 'renderview/release';

export function lowcodeOrganizationURL(
  { route = 'hlod', isSite, haveGrade = 'v1', withoutOrgid = false } = {
    route: 'hlod',
    withoutOrgid: false,
  } as any
) {
  const _isSite = (() => {
    if (withoutOrgid) return true;
    if (isBoolean(isSite)) return isSite;
    return !isTenantRoleLevel();
  })();
  const orgStr = _isSite ? '' : `${getCurrentOrganizationId()}`;
  return `${((window as any).__lowcodeUrlRoute || {})[route] || route}${
    haveGrade ? `/${haveGrade}` : ''
  }${orgStr ? `/${orgStr}` : ''}`;
}

export const getLovDefineAxiosConfig = ({ lovType, businessObjectOptionCode }) => {
  if (lovType === 'BUSINESS_OBJECT_OPTION') {
    return (code, dataSet) => {
      const lovConfig = lovDefineAxiosConfig(code, dataSet as any);
      const isPublishPage =
        window?.location?.href?.indexOf(PreviewPageUrlSuffix) === -1 &&
        window?.location?.href?.indexOf(PreviewReleasePageUrlSuffix) === -1 &&
        window?.location?.href?.indexOf('authority-app-preview') === -1;
      return {
        ...lovConfig,
        method: 'GET',
        url: `/${lowcodeOrganizationURL({
          route: 'hmde',
        })}/executor/option/${businessObjectOptionCode}/view-info`,
        params: filterNullValueObject({
          dataObjectCode: dataSet?.record?.get('__feidaDataObjectCode'),
          dataObjectOptionCode: dataSet?.record?.get('__feidaDataObjectCode') ? code : undefined,
          publishFlag: isPublishPage,
        }),
      };
    };
  }
  return undefined;
};

export const getCookies = (name) => {
  const reg = new RegExp(`(^| )${name}=([^;]*)(;|$)`);
  const result = (document.cookie || '').match(reg);
  if (result && result[2]) {
    return unescape(result[2]);
  }
  return '{}';
};

export const getSessionAppInfo = (path?: string) => {
  const result = getCookies(path || 'appInfo'); // 暂时先从cookie中获取
  try {
    return JSON.parse(result);
  } catch (error) {
    window.location = `${window.location.protocol}//${window.location.host}${process.env.BASE_PATH}pub/hlod/authority/authority-manage` as any;
    throw new Error(error as any);
  }
};

export function getAppId() {
  const { appId } = JSON.parse(sessionStorage.getItem('appInfo') || '{}'); // 先从session中获取
  // eslint-disable-next-line no-self-compare
  if (!appId || appId !== appId) {
    // window.location = `${window.location.protocol}//${window.location.host}${process.env.BASE_PATH}pub/hlod/authority/authority-manage`;
    const cookieAppId = getSessionAppInfo().appId;

    // eslint-disable-next-line no-self-compare
    if (cookieAppId && cookieAppId === cookieAppId) {
      // 过滤 NaN
      return cookieAppId;
    }

    // console.error('appId未获取。请通过正常流程选择应用进入页面，或者询问技术人员。')
    return;
  }
  return appId;
}

export function getDraftFlag() {
  return 1; // draft-flag 拟定态传1 运行传0 20200601
}


export function lookupConfig(lookupData, lovPara = {}) {
  const { tenantId } = getCurrentTenant();

  const {
    routeName = '',
    customUrl = '',
    lookupCode,
    lovTypeCode = 'IDP',
    from,
    appId,
  } = lookupData;
  const organizationRe = /\/{organizationId\}|\/{tenantId\}/g;
  const newUrl = organizationRe.test(customUrl)
    ? customUrl?.replace(organizationRe, `/${getCurrentOrganizationId()}`)
    : customUrl?.replace(organizationRe, '');
  const lookupUrl = {
    IDP: {
      url:
        from === 'lov'
          ? `/${lowcodeOrganizationURL({ route: 'hpfm' })}/lovs/value/page`
          : `/${lowcodeOrganizationURL({ route: 'hpfm' })}/lovs/value`,
      params: {
        lovCode: lookupCode,
        tenantId,
        'app-id': appId || getAppId(),
        'draft-flag': getDraftFlag(),
      },
    },
    URL: {
      url: `/${routeName}${newUrl}`,
      params: {
        page: from === 'lov' ? undefined : 0,
        size: from === 'lov' ? undefined : 999,
        tenantId,
        'app-id': appId || getAppId(),
        'draft-flag': getDraftFlag(),
        ...lovPara,
      },
    },
    SQL: {
      url: `/${lowcodeOrganizationURL({ route: routeName })}/lovs/sql/data`,
      params: {
        lovCode: lookupCode,
        tenantId,
        page: from === 'lov' ? undefined : 0,
        size: from === 'lov' ? undefined : 999,
        'app-id': appId || getAppId(),
        'draft-flag': getDraftFlag(),
        ...lovPara,
      },
    },
  };

  const objToSearch = (obj) => {
    let search = '';
    Object.keys(obj).forEach((k) => {
      if (obj[k] !== undefined && obj[k] !== null) {
        search += `${search ? '&' : ''}${k}=${obj[k]}`;
      }
    });
    return search;
  };

  return {
    url: `${lookupUrl[lovTypeCode].url}${
      lookupUrl?.[lovTypeCode]?.url?.indexOf?.('?') > -1 ? '&' : '?'
    }${objToSearch(lookupUrl[lovTypeCode].params)}`,
    method: 'GET',
  };
};

/**
 * 获取lov查询接口
 * @param param0
 */
export const getLovQueryAxiosConfig = ({ viewCode }) => {
  if (viewCode) {
    return (code, config: any): any => {
      const [, routeName, ...other] = config?.originData?.queryUrl?.split?.('/') || [];
      return lookupConfig({
        appId: getAppId(),
        from: 'lov',
        routeName,
        customUrl: `/${other.join('/')}`,
        lovTypeCode: config?.originData?.lovTypeCode,
        lookupCode: config?.originData?.lovCode,
        size: 10,
      });
    };
  }
  return undefined;
};
